#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2023/12/29 17:39
# @Author  : 胡浩浩
# @File    : report_router.py
# @IDE     : PyCharm
# @description :
from datetime import datetime
from typing import List

from fastapi import APIRouter, Query

from backend.app.models.report_model import ReportModel, ReportPage, ReportIn
from backend.app.utils.response_tepmlate import ResponseCode

report_router = APIRouter(prefix="/report", tags=["测试报告管理"])


@report_router.post("/add")
async def create_report(report: ReportIn):
    select_report = await ReportModel.filter(url=report.url).first()
    if select_report:
        return ResponseCode(report.url).response_409()
    else:
        new_report = await ReportModel.create(
            url=report.url,
            created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        )
        return ResponseCode(new_report.url).response_add()


# 定义 API 路由
@report_router.get("/page", response_model=ReportPage)
async def get_Report_page_list(
        page: int = Query(1, ge=1),
        size: int = Query(10, ge=1, le=100),
        url: str = Query(None, min_length=0)
):
    skip = (page - 1) * size
    query = ReportModel.all()
    if url:
        query = query.filter(url__icontains=url)
    total = await query.count()
    Reports = await query.offset(skip).limit(size).values()
    return ReportPage(total=total, page_size=size, current_page=page, search_key=url, results=Reports)
